const mongoose = require('mongoose')
const chalk = require('chalk');
const PORT = 27017

// const URL = 'user01:123456@112.126.103.197'
const URL = '124.222.176.177'
const DB = 'lc_mall'
mongoose.set('useCreateIndex', true)
//连接数据库
mongoose.connect(`mongodb://${URL}:${PORT}/${DB}`, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false
})
const db = mongoose.connection;

db.once('open' ,() => {
	console.log(
    chalk.green('连接数据库成功')
  );
})

db.on('error', function(error) {
    console.error(
      chalk.red('Error in MongoDb connection: ' + error)
    );
    mongoose.disconnect();
});

db.on('close', function() {
    console.log(
      chalk.red('数据库断开')
    );
    // mongoose.connect(`mongodb://${URL}:${PORT}/${DB}`, {server:{auto_reconnect:true}});
});

module.exports = db